package cn.org.donald.service.impl;

import cn.org.donald.framework.constant.FileConstant;
import cn.org.donald.framework.util.BeanUtil;
import cn.org.donald.framework.util.FileUtil;
import cn.org.donald.mapper.TableFileMapper;
import cn.org.donald.mapper.UserMapper;
import cn.org.donald.pojo.entity.system.TableFile;
import cn.org.donald.pojo.entity.system.User;
import cn.org.donald.service.system.TableFileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.dubbo.config.annotation.Service;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author : Donald
 * @since : 2020/12/14 15:14
 */
@Service(version = "1.0.0", group = "donald")
public class TableFileServiceImpl implements TableFileService {

    @Autowired
    private TableFileMapper tableFileMapper;

    @Autowired
    private UserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(TableFileServiceImpl.class);

    /**
     * 文件信息表新增
     *
     * @param tableFile
     * @return
     */
    @Override
    public boolean addFile(TableFile tableFile) {
        return tableFileMapper.insert(tableFile) > 0;
    }

    /**
     * 清理文件
     * 用户id不存在时删除
     *
     * @return
     */
    @Override
    public int cleanFileByUserId() {
        QueryWrapper<TableFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("user_id");
        List<TableFile> tableFiles = tableFileMapper.selectList(queryWrapper);
        return tableFiles.stream().mapToInt(tableFile -> {
            User user = userMapper.selectById(tableFile.getUserId());
            if (BeanUtil.isEmptyOrClassFieldAllEmpty(user)) {
                // TODO 删除不存在用户的相关文件
                String realPath = tableFile.getRealPath();// 文件真实地址
                File file = new File(realPath);
                if (file.exists()) {
                    return file.delete()? 1 : 0;
                }
            }
            return 0;
        }).sum();
    }

    /**
     * 根据文件名称清理文件
     *
     * 文件名不存在时删除
     */
    @Override
    public int cleanFileByFileName() {
        String filePathUpload = FileConstant.FILE_PATH_UPLOAD;
        File file = new File(filePathUpload);
        String[] fileNames = file.list();
        if (fileNames == null){
            logger.info("该目录下没有文件");
            return 0;
        }
        if (fileNames.length>0){
            return Arrays.stream(fileNames).mapToInt(fileName -> {
                boolean isFileExist = tableFileMapper.isExistByFileName(fileName);
                if (!isFileExist){
                    String fileRealPath = filePathUpload + FileUtil.separator + fileName;
                    File file1 = new File(fileRealPath);
                    if (file1.exists()){
                        boolean delete = file1.delete();
                        return delete ? 1 : 0;
                    }
                }
                return 0;
            }).sum();
        }
        return 0;
    }
}
